<template>
  <div class="left">
    <div class="left-bg">
      <div class="title-box" v-for="item in titleList" :key="item">
        <el-popover
          popper-class="jsc-popper-style"
          v-if="item === '气象监测'"
          placement="right"
          :width="91"
          trigger="click"
        >
          <template #reference>
            <div
              class="title-box"
              :class="{ 'title-active': title === item }"
              @click="
                () => {
                  titleClick(item)
                  popoverVisible = true
                }
              "
            >
              {{ item }}
            </div>
          </template>
          <ul class="meteorological-list">
            <li
              :class="{ 'meteorological-active': meteorologicalis === year }"
              v-for="year in meteorologicalList"
              :key="year"
              @click="selectMeteorological(year)"
            >
              {{ year }}
            </li>
          </ul>
        </el-popover>

        <div
          v-else
          class="title-box"
          :class="{ 'title-active': title === item }"
          @click="
            () => {
              titleClick(item)
              popoverVisible = false
            }
          "
        >
          {{ item }}
        </div>
      </div>
    </div>
  </div>
  <div class="right">
    <div class="right-top">
      <div class="right-top-bg">
        <img src="@/assets/img/jsc/qsyc.png" alt="" />
      </div>
      <div class="right-top-box">
        <div class="right-box-item" v-for="(item, index) in weather" :key="index">
          <div class="day-box">
            {{ item.dayDescription }} {{ dayjs(item.recordDate).format('MM-DD') }}
          </div>
          <div class="wind-box">
            <img class="wind-box-img" :src="getAssetsFile('jsc', item.img)" />
            <div class="wind-box-wd">{{ item.temperature }}℃</div>
            <div class="wind-box-ms">{{ item.weatherConditions }} {{ item.precipitation }}</div>
            <div class="wind-box-kl">{{ item.windDirection }} {{ item.windSpeed }}</div>
            <div class="wind-box-zl">湿度 {{ item.humidity }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="right-middle">
      <div class="right-top-bg">
        <img src="@/assets/img/jsc/mbcs.png" alt="" />
      </div>
      <div class="right-middle-box">
        <div class="right-middle-top">
          <div class="right-middle-top-item right-middle-red">
            <div class="right-middle-red-top">目标ID</div>
            <div class="right-middle-red-middle">00000000</div>
            <div class="right-middle-red-bottom">设备名称</div>
          </div>
          <div class="right-middle-top-item">
            <div class="right-middle-blue right-middle-blue-top">
              <div class="right-middle-blue-top-text">XXX</div>
              <div class="right-middle-blue-top-num">32%</div>
            </div>
            <div class="right-middle-blue">
              <div class="right-middle-blue-top-text">XXX</div>
              <div class="right-middle-blue-top-num">32%</div>
            </div>
          </div>
          <div class="right-middle-top-item">
            <div class="right-middle-blue right-middle-blue-top">
              <div class="right-middle-blue-top-text">XXX</div>
              <div class="right-middle-blue-top-num">32%</div>
            </div>
            <div class="right-middle-blue">
              <div class="right-middle-blue-top-text">XXX</div>
              <div class="right-middle-blue-top-num">32%</div>
            </div>
          </div>
        </div>
        <div class="right-middle-bottom">
          <div class="right-middle-bottom-item">
            <div class="right-middle-bottom-item-top">经度</div>
            <div class="right-middle-bottom-item-bottom">123.45.46</div>
          </div>
          <div class="right-middle-bottom-item right-middle-bottom-item-middle">
            <div class="right-middle-bottom-item-top">纬度</div>
            <div class="right-middle-bottom-item-bottom">123.45.46</div>
          </div>
          <div class="right-middle-bottom-item">
            <div class="right-middle-bottom-item-top">范围</div>
            <div class="right-middle-bottom-item-bottom">123.45.46</div>
          </div>
          <div class="right-middle-bottom-line line-one"></div>
          <div class="right-middle-bottom-line line-two"></div>
        </div>
      </div>
    </div>
    <div class="right-bottom">
      <div class="right-bottom-bg">
        <img class="right-bottom-img" src="@/assets/img/jsc/sgqk.png" alt="" />
        <div class="right-bottom-qh" @click="qhClick">切换</div>
      </div>
      <div v-show="showAccident == true">
        <div class="right-bottom-top">
          <div style="width: 100%; height: 100%" ref="chartAccident"></div>
        </div>
        <div class="right-bottom-line"></div>
        <div class="right-bottom-bottom">
          <div class="right-bottom-bottom-title">
            <div class="right-bottom-bottom-title-left">
              <div class="right-bottom-bottom-title-left-text">
                {{ typeof yearis == 'number' ? yearis : '' }}年度统计
              </div>
              <el-popover
                popper-class="jsc-popper-style"
                @show="activeRl = true"
                @hide="activeRl = false"
                placement="right"
                :width="91"
                trigger="click"
              >
                <template #reference>
                  <img v-if="!activeRl" src="@/assets/img/jsc/rl.png" alt="" />
                  <img v-if="activeRl" src="@/assets/img/jsc/rlactive.png" alt="" />
                </template>
                <ul class="year-list">
                  <li :class="{ 'year-active': yearis === '全部' }" @click="selectYear('全部')">
                    全部
                  </li>
                  <li
                    :class="{ 'year-active': yearis === year }"
                    v-for="year in years"
                    :key="year"
                    @click="selectYear(year)"
                  >
                    {{ year }}
                  </li>
                </ul>
              </el-popover>
            </div>
            <div class="right-bottom-bottom-title-right">
              <img src="@/assets/img/jsc/jx.png" alt="" />
              <div class="right-bottom-bottom-title-right-text">事件数量</div>
            </div>
          </div>
          <div class="right-bottom-bottom-chart">
            <div style="width: 100%; height: 100%" ref="chartAccidentyear"></div>
          </div>
        </div>
      </div>
      <div v-show="showAccident == false">
        <div class="right-bottom-table">
          <div class="table-container">
            <table class="table">
              <thead>
                <tr>
                  <th class="table-index table-head">序号</th>
                  <th class="table-item table-head">事件名称</th>
                  <th class="table-item table-head">事件类型</th>
                  <th class="table-time table-head">时间</th>
                </tr>
              </thead>
            </table>
            <div class="content-wrapper">
              <swiper
                :direction="'vertical'"
                :slides-per-view="3"
                :space-between="12"
                :loop="isLoop"
                :autoplay="isLoop ? { delay: 3000, disableOnInteraction: false } : false"
                class="swiper-table"
                :modules="[Autoplay]"
              >
                <swiper-slide
                  v-for="(item, index) in displayData"
                  :key="index"
                  :class="swiperIndex === index ? 'swiper-active' : ''"
                  class="swiper-slide-item"
                  @click="clickSwiperItem(index)"
                >
                  <table class="table table-body">
                    <tbody>
                      <tr>
                        <td class="table-index">{{ index + 1 }}</td>
                        <td class="table-name">{{ item.simulationName }}</td>
                        <td class="table-type">{{ item.simulationType }}</td>
                        <td class="table-time">{{ item.trainingTime }}</td>
                      </tr>
                    </tbody>
                  </table>
                </swiper-slide>
              </swiper>
            </div>
          </div>
        </div>
        <div class="right-bottom-line"></div>
        <div class="right-bottom-injury">
          <!-- <div style="width: 100%; height: 100%;" ref="chartInjury"></div> -->
          <div class="right-bottom-injury-chart" ref="chartInjury"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
defineOptions({
  name: 'jsc', // 添加组件名称
})
import {
  ref,
  onMounted,
  onBeforeUnmount,
  onActivated,
  onDeactivated,
  computed,
  watch,
  nextTick,
} from 'vue'
import { mockMaterialData, mockDeviceData } from '@/mock/dataSimulator'
import { dayjs } from 'element-plus'
import {
  getaccidentList,
  getaccidentChart,
  getaccidentStrip,
  getaccidentPersonList,
  getweatherWind,
  getwarehouseList,
  getPopulationList,
} from '@/api'
import { getAssetsFile } from '@/utils/compnt'
import { Swiper, SwiperSlide } from 'swiper/vue'
import { Autoplay } from 'swiper/modules'
import 'swiper/css'
import * as echarts from 'echarts'
import nq from '@/assets/img/jsc/nq.png'
import LayerManager from './LayerManager'
import datas from './1'
const titleList = ref(['物资库', '气象监测', '监测设备', '人口分布'])

const title = ref('物资库')
const years = ref([])
const currentYear = new Date().getFullYear()
const startYear = 2005
for (let y = currentYear; y >= startYear; y--) {
  years.value.push(y)
}
const selectYear = async (year) => {
  yearis.value = year
  activeRl.value = false
  console.log('year', typeof year)
  yearParametersdata.value = year

  // 这里可以添加你点击年份后的逻辑，比如关闭弹窗、更新显示等
  if (showAccident.value) {
    await getshijian()
    await updateChartAccident()
    await getshijiantongji()
    await updateChartAccidentyear()
  }
}
const meteorologicalis = ref('')
const selectMeteorological = (year) => {
  meteorologicalis.value = year
  // 这里可以添加你点击年份后的逻辑，比如关闭弹窗、更新显示等
}
const meteorologicalList = ref(['温度', '湿度', '雨量', '风场', '降雨过程'])
const yearis = ref('全部')
const activeRl = ref(false)
const chartAccident = ref(null)
const chartAccidentyear = ref(null)
const chartInjury = ref(null)
let chartAccidentInstance = null
let chartAccidentYearInstance = null
let chartInjuryInstance = null

// const weather = ref(
//   [
//     {
//       time: '今天 08/06',
//       img: '@/assets/img/jsc/晴天.png',
//       value: '20~30℃',
//       name: '晴天',
//       pm: 'PM2.3',
//       airQuality: '空气质量 优',
//     },
//     {
//       time: '今天 08/06',
//       img: '@/assets/img/jsc/晴天.png',
//       value: '20~30℃',
//       name: '晴天',
//       pm: 'PM2.3',
//       airQuality: '空气质量 优',
//     },
//     {
//       time: '今天 08/06',
//       img: '@/assets/img/jsc/晴天.png',
//       value: '20~30℃',
//       name: '晴天',
//       pm: 'PM2.3',
//       airQuality: '空气质量 优',
//     }
//   ]
// )
// const titleClick = async (item) => {
// }
// layerManager.value = new LayerManager(viewer.value);
// console.log('layerManager', layerManager)
const weather = ref([])

// 获取当前日期
const getDayInfo = (date) => {
  const now = new Date()
  const targetDate = new Date(date)

  // 计算两个日期的差值（以天为单位）
  const diffTime = Math.abs(targetDate - now)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

  // 根据差值判断是今天、明天还是后天
  if (targetDate.toDateString() === now.toDateString()) {
    return '今天'
  } else if (diffDays === 1 && targetDate > now) {
    return '明天'
  } else if (diffDays === 2 && targetDate > now) {
    return '后天'
  }
  return targetDate.toLocaleDateString()
}

// 在获取天气数据后添加天数判断
const getweatherWindapi = async () => {
  const { data } = await getweatherWind()

  getDayInfo(data[0]?.recordDate)
  if (data && Array.isArray(data)) {
    data.forEach((item) => {
      if (item.recordDate) {
        // 假设 recordDate 是日期字符串，可根据实际情况调整
        item.dayDescription = getDayInfo(item.recordDate)
      }
    })
  }

  weather.value = data
}
const cameraChangeListener = ref(null)
const currentDisplayLevel = ref(0) // 0表示国家级，1表示省级

const titleClick = async (item) => {
  title.value = item
  console.log('title.value', title.value)
  if (item === '物资库') {
    const res = await getwarehouseList()
    // const data = await mockMaterialData(30) // 生成25条物资库数据
    // console.log('data', data)
    // console.log('res', res)
    // console.log('res', res.data)
    layerManager.value.showLayer('material', res.data)
  } else if (item === '监测设备') {
    const res = await mockDeviceData(25) // 生成25条物资库数据
    layerManager.value.showLayer('device', res.data)
  } else if (item === '人口分布') {
    showPopulationDistributionByLevel(0) // 默认显示国家级
    setupCameraListener() // 设置相机监听器实现层级切换
  }
}
// 根据层级显示人口分布
function showPopulationDistributionByLevel(level) {
  console.log('显示人口分布层级：', level)
  clearPopulationEntities()
  currentDisplayLevel.value = level

  let levelFeatures = []

  if (level === 0) {
    // 国家级别(level=0) - 直接从顶层features获取
    levelFeatures = datas.features.filter((f) => f.properties.level === 0)
  } else if (level === 1) {
    // 省级(level=1) - 需要从level=0的children中获取
    datas.features
      .filter((f) => f.properties.level === 0) // 找到国家层级
      .forEach((country) => {
        if (country.properties.children) {
          // 从国家的children中获取省级数据
          const provinceFeatures = country.properties.children.filter(
            (child) => child.properties.level === 1,
          )
          levelFeatures = levelFeatures.concat(provinceFeatures)
        }
      })
  } else if (level === 2) {
    // 市级(level=2) - 需要从level=1的children中获取
    datas.features
      .filter((f) => f.properties.level === 0) // 找到国家层级
      .forEach((country) => {
        if (country.properties.children) {
          // 遍历省级数据
          country.properties.children
            .filter((province) => province.properties.level === 1)
            .forEach((province) => {
              if (province.properties.children) {
                // 从省级的children中获取市级数据
                const cityFeatures = province.properties.children.filter(
                  (child) => child.properties.level === 2,
                )
                levelFeatures = levelFeatures.concat(cityFeatures)
              }
            })
        }
      })
  } else if (level === 3) {
    // 区县级(level=3) - 需要从level=2的children中获取
    datas.features
      .filter((f) => f.properties.level === 0) // 找到国家层级
      .forEach((country) => {
        if (country.properties.children) {
          // 遍历省级数据
          country.properties.children
            .filter((province) => province.properties.level === 1)
            .forEach((province) => {
              if (province.properties.children) {
                // 遍历市级数据
                province.properties.children
                  .filter((city) => city.properties.level === 2)
                  .forEach((city) => {
                    if (city.properties.children) {
                      // 从市级的children中获取区县数据
                      const districtFeatures = city.properties.children.filter(
                        (child) => child.properties.level === 3,
                      )
                      levelFeatures = levelFeatures.concat(districtFeatures)
                    }
                  })
              }
            })
        }
      })
  }

  if (levelFeatures.length === 0) {
    console.log('未找到level=' + level + '的数据')
    return
  }

  // 计算最大人口数用于高度缩放
  const populations = levelFeatures.map((f) => f.properties.population)
  const maxPopulation = Math.max(...populations)
  // 根据不同层级设置不同的高度缩放比例
  let heightScale
  if (level === 0) {
    heightScale = 3000000 / maxPopulation
  } else if (level === 1) {
    heightScale = 1500000 / maxPopulation
  } else if (level === 2) {
    heightScale = 800000 / maxPopulation
  } else {
    // level 3 (区县级)
    heightScale = 400000 / maxPopulation
  }

  // 为每个区域创建柱状图
  levelFeatures.forEach((feature) => {
    const position = feature.geometry.position
    const population = feature.properties.population
    const name = feature.properties.name

    // 计算柱子高度
    const columnHeight = population * heightScale
    const longitude = position[0]
    const latitude = position[1]

    // 根据不同层级设置不同的柱子半径和字体大小
    let topRadius, bottomRadius, font
    if (level === 0) {
      topRadius = 30000.0
      bottomRadius = 30000.0
      font = '14px sans-serif'
    } else if (level === 1) {
      topRadius = 20000.0
      bottomRadius = 20000.0
      font = '12px sans-serif'
    } else if (level === 2) {
      topRadius = 10000.0
      bottomRadius = 10000.0
      font = '10px sans-serif'
    } else {
      // level 3 (区县级)
      topRadius = 5000.0
      bottomRadius = 5000.0
      font = '8px sans-serif'
    }

    // 创建柱状图实体
    try {
      window.viewer.entities.add({
        id: `population_${name}_${level}`,
        name: name,
        position: window.Cesium.Cartesian3.fromDegrees(longitude, latitude, columnHeight / 2),
        cylinder: {
          length: columnHeight,
          topRadius: topRadius,
          bottomRadius: bottomRadius,
          material: getColorByPopulation(population, maxPopulation),
          outline: true,
          outlineColor: window.Cesium.Color.WHITE.withAlpha(0.8),
          shadows: window.Cesium.ShadowMode.ENABLED,
        },
        label: {
          text: `${name}\n${(population / 10000).toFixed(0)}万人`,
          font: font,
          fillColor: window.Cesium.Color.WHITE,
          outlineColor: window.Cesium.Color.BLACK,
          outlineWidth: 2,
          style: window.Cesium.LabelStyle.FILL_AND_OUTLINE,
          verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new window.Cesium.Cartesian2(0, 20),
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
        },
      })
    } catch (error) {
      console.error('Error creating population entity:', error)
    }
  })
}

// 设置相机监听器实现层级切换
function setupCameraListener() {
  // 清除之前的监听器
  if (cameraChangeListener.value) {
    cameraChangeListener.value()
    cameraChangeListener.value = null
  }

  // 添加新的相机监听器
  cameraChangeListener.value = window.viewer.camera.changed.addEventListener(() => {
    const height = window.viewer.camera.positionCartographic.height
    let targetLevel = 0

    // 根据相机高度确定显示层级
    if (height < 1000000) {
      targetLevel = 3 // 区县级
    } else if (height < 2000000) {
      targetLevel = 2 // 市级
    } else if (height < 5000000) {
      targetLevel = 1 // 省级
    } else {
      targetLevel = 0 // 国家级
    }

    // 当层级发生变化时更新显示
    if (targetLevel !== currentDisplayLevel.value) {
      showPopulationDistributionByLevel(targetLevel)
    }
  })
}

// 根据人口数量返回颜色
function getColorByPopulation(population, maxPopulation) {
  const ratio = Math.min(population / maxPopulation, 1)
  // 从浅蓝到深红的渐变
  const red = Math.min(ratio * 2, 1)
  const green = Math.max(0, 1 - Math.abs(ratio - 0.5) * 2)
  const blue = Math.max(0, 1 - ratio * 1.5)
  return new window.Cesium.Color(red, green, blue, 0.8)
}

// 清除已有的人口分布实体
function clearPopulationEntities() {
  if (window.viewer) {
    const entitiesToRemove = []
    window.viewer.entities.values.forEach((entity) => {
      if (entity.id && entity.id.startsWith('population_')) {
        entitiesToRemove.push(entity)
      }
    })

    entitiesToRemove.forEach((entity) => {
      try {
        window.viewer.entities.remove(entity)
      } catch (error) {
        console.warn('Error removing entity:', error)
      }
    })
  }
}

let timer = null
// 事件统计饼图
const initChartAccident = async () => {
  if (!chartAccident.value) return
  chartAccident.value.clientWidth // 触发重绘
  chartAccidentInstance = echarts.init(chartAccident.value)
  updateChartAccident()
}
const initChartInjury = async () => {
  if (!chartInjury.value) return
  chartInjury.value.clientWidth // 触发重绘
  chartInjuryInstance = echarts.init(chartInjury.value)
  updateChartInjury()
}
// 更新事件统计饼图
const updateChartInjury = async () => {
  if (!chartInjury.value) return

  const text = injuryDataTotal.value.toString()
  // 大概每个字符占 10px 宽度（根据字体大小调整）
  const textWidth = text.length * 10
  // 饼图中心 x 坐标 - 文本一半宽度 = 实际 left 值
  const leftPos = 73 - textWidth / 2
  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 150,
      top: 'center',
      itemGap: 26,
      itemWidth: 8,
      itemHeight: 8,
      textStyle: {
        fontSize: 10,
        color: '#D0DEEE',
        rich: {
          name: {
            width: 80,
            color: 'rgba(208, 222, 238, 1)',
            fontSize: 10,
            padding: [0, 0, 0, 8],
          },
          value: {
            width: 50,
            color: 'rgba(208, 222, 238, 1)',
            align: 'right',
            fontSize: 11,
            fontWeight: 'normal',
          },
        },
      },
      formatter: (name) => {
        const item = injuryData.value.find((d) => d.name === name)
        const percent = ((item.value / injuryDataTotal.value) * 100).toFixed(1)
        return `{name|${name}}{value|${percent}%}`
      },
    },
    series: [
      {
        name: '外环',
        type: 'pie',
        radius: ['90%', '100%'], // 外环半径比饼图大一点
        center: [75, '50%'],
        silent: true, // 不响应鼠标事件
        label: { show: false },
        data: [{ value: 1, itemStyle: { color: 'rgba(255, 255, 255, 0.1)' } }],
      },
      {
        type: 'pie',
        radius: ['70%', '85%'],
        center: [75, '50%'],
        avoidLabelOverlap: false,
        padAngle: 5,
        itemStyle: {
          borderRadius: 0,
          borderColor: 'transparent',
          borderWidth: 0,
        },
        label: {
          show: false,
          position: 'center',
        },
        // emphasis: {
        //   label: {
        //     show: true,
        //     fontSize: 20,
        //     fontWeight: 'bold',
        //     formatter: (params) => {
        //       const percent = ((params.value / injuryDataTotal.value) * 100).toFixed(1);
        //       return `${percent}%`;
        //     }
        //   }
        // },
        labelLine: {
          show: false,
        },
        data: injuryData.value,
      },
    ],
    graphic: [
      {
        type: 'image',
        id: 'centerImages',
        left: 29,
        top: 'center',
        z: 100,
        style: {
          image: nq, // 替换成你的图片链接
          width: 91,
          height: 92,
          // borderRadius: 40 // 让图片圆形
        },
      },
      {
        type: 'group',
        left: 165,
        top: 'center',
        children: injuryData.value.map((item, index) => ({
          type: 'rect',
          shape: {
            x: 10,
            y: index * 37,
            width: 200,
            height: 20,
            r: 0,
          },
          style: {
            fill: 'rgba(240, 242, 245, 0.06)',
          },
          z: -1,
        })),
      },
      {
        type: 'text',
        id: 'totalValueText', // 添加唯一ID
        left: leftPos,
        top: '40%',
        style: {
          text: injuryDataTotal.value.toString(),
          fill: '#D0DEEE',
          fontSize: 18,
          fontWeight: 'bold',
          align: 'center',
          textAlign: 'center',
        },
      },
      {
        type: 'text',
        id: 'totalValueTotal', // 添加唯一ID
        left: 58,
        top: '55%',
        style: {
          text: '总人数',
          fill: '#D0DEEE',
          fontSize: 10,
          fontWeight: 'bold',
          align: 'center',
        },
      },
    ],
  }
  chartInjuryInstance.setOption(option)
}

const updateChartAccident = async () => {
  if (!chartAccident.value) return
  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 150,
      top: 'center',
      itemGap: 26,
      itemWidth: 8,
      itemHeight: 8,
      textStyle: {
        fontSize: 10,
        color: '#D0DEEE',
        rich: {
          name: {
            width: 80,
            color: 'rgba(208, 222, 238, 1)',
            fontSize: 10,
            padding: [0, 0, 0, 8],
          },
          value: {
            width: 50,
            color: 'rgba(208, 222, 238, 1)',
            align: 'right',
            fontSize: 11,
            fontWeight: 'normal',
          },
        },
      },
      formatter: (name) => {
        const item = accidentData.value.find((d) => d.name === name)
        // return `{name|${name}}{value|${item.value}%}`;

        const percent = ((item.value / accidentDataTotal.value) * 100).toFixed(1)
        return `{name|${name}}{value|${percent}%}`
      },
    },
    series: [
      {
        name: '外环',
        type: 'pie',
        radius: ['90%', '100%'], // 外环半径比饼图大一点
        center: [73, '50%'],
        silent: true, // 不响应鼠标事件
        label: { show: false },
        data: [{ value: 1, itemStyle: { color: 'rgba(255, 255, 255, 0.1)' } }],
      },
      {
        // name: 'Access From',
        type: 'pie',
        radius: ['70%', '85%'],
        center: [73, '50%'],
        avoidLabelOverlap: false,
        padAngle: 5,
        itemStyle: {
          borderRadius: 0,
          borderColor: 'transparent',
          borderWidth: 0,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold',
            formatter: (params) => {
              const percent = ((params.value / accidentDataTotal.value) * 100).toFixed(1)
              return `${percent}%`
            },
          },
        },
        labelLine: {
          show: false,
        },
        data: accidentData.value,
      },
    ],
    graphic: [
      {
        type: 'image',
        id: 'centerImage',
        left: 27,
        top: 'center',
        z: 100,
        style: {
          image: nq, // 替换成你的图片链接
          width: 91,
          height: 92,
          // borderRadius: 40 // 让图片圆形
        },
      },
      {
        type: 'group',
        left: 155,
        top: 'center',
        children: accidentData.value.map((item, index) => ({
          type: 'rect',
          shape: {
            x: 10,
            y: index * 37,
            width: 200,
            height: 20,
            r: 0,
          },
          style: {
            fill: 'rgba(240, 242, 245, 0.06)',
          },
          z: -1,
        })),
      },
    ],
  }
  chartAccidentInstance.setOption(option)
}
// 初始化事件年度统计图
const initChartAccidentyear = async () => {
  if (!chartAccidentyear.value) return
  chartAccidentyear.value.clientWidth // 触发重绘
  chartAccidentYearInstance = echarts.init(chartAccidentyear.value)

  updateChartAccidentyear()
}
// 更新事件年度统计图
const updateChartAccidentyear = async () => {
  if (!chartAccidentyear.value) return
  const maxHeight = 400 // 容器高度，方便计算顶部高亮比例
  const topHighlightPx = 4
  const topHighlightRatio = topHighlightPx / maxHeight // 顶部高亮线条占比

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        // console.log(params);
        // params 是一个数组，包含当前悬浮点的所有系列数据
        let res = `<div style="color:#ff6600;">${params.name}</div>`
        res += `<div>${params.marker} 事件总数: <span style="color:#00ff00;">${params.value}</span></div>`
        return res
      },
    },
    xAxis: {
      type: 'category',
      // data: data.map(item => item.year),
      data: accidentYrarData.value.map((item) => item.year),
      axisTick: { alignWithLabel: true },
      axisLabel: {
        color: '#D0DEEE', // X轴文字颜色
        interval: 0,
      },
      axisLine: {
        lineStyle: {
          color: '#6C8097', // X轴轴线颜色也设置为一致，增强视觉统一
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 9,
        color: '#6C8097',
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed', // 虚线
          color: 'rgba(108, 128, 151, 0.30)', // 颜色
        },
      },
    },
    grid: {
      top: 20, // 距离容器顶部40px
      bottom: 5, // 距离容器底部50px
      left: 10, // 距离容器左侧60px
      right: 10, // 距离容器右侧30px
    },
    series: [
      {
        type: 'bar',
        data: accidentYrarData.value.map((item) => item.value),
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(108, 128, 151, 0.1)',
        },
        label: {
          show: true, // 显示标签
          position: 'top', // 标签位置在柱子顶部
          color: '#FFFFFF', // 标签文字颜色，可以根据需求调整
          fontSize: 11, // 文字大小
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#159AFF' }, // 顶部高亮色，模拟box-shadow的inset线条
            { offset: topHighlightRatio, color: '#159AFF' },
            { offset: topHighlightRatio + 0.01, color: 'rgba(0,58,255,0)' }, // 透明渐变开始
            { offset: 1, color: '#159AFF' }, // 底部纯色
          ]),
        },
        barWidth: '40%',
      },
    ],
  }
  chartAccidentYearInstance.setOption(option)
}
// 事件表格
const showAccident = ref(true)

const qhClick = async () => {
  showAccident.value = !showAccident.value
  await nextTick()
  if (showAccident.value) {
    await getshijian()
    await initChartAccident()
    await getshijiantongji()
    await initChartAccidentyear()
  } else {
    await getshangqing()
    await initChartInjury()
    await getaccidentListapi()
  }
}

const accidentData = ref([])
const accidentDataTotal = ref(0)
const yearParametersdata = ref('' || '全部')
const getshijian = async () => {
  if (yearParametersdata.value == '全部') {
    yearParametersdata.value = yearParametersdata.value + '-' + new Date().getFullYear()
  }
  const { data } = await getaccidentChart({
    yearParameters: yearParametersdata.value,
  })
  let accident = data.map((item) => {
    return {
      name: item.typeName,
      value: item.typeNum,
    }
  })

  accidentData.value = accident

  accidentDataTotal.value = accidentData.value.reduce((sum, item) => sum + item.value, 0)
}
const injuryData = ref([])
const injuryDataTotal = ref(0)

const getshangqing = async () => {
  //  injuryData = await getshangqing()

  const { data } = await getaccidentPersonList()
  let PersonList = data.map((item) => {
    return {
      value: item.personCount,
      name: item.personType,
    }
  })
  injuryData.value = PersonList

  // [
  //   { value: 500, name: '轻度伤情' },
  //   { value: 400, name: '中度伤情' },
  //   { value: 30, name: '重度伤情' },
  //   { value: 20, name: '死亡' }
  // ]
  injuryDataTotal.value = injuryData.value.reduce((sum, item) => sum + item.value, 0)
  console.log('injuryDataTotal', injuryDataTotal.value)
}
const accidentYrarData = ref([])

const getshijiantongji = async () => {
  const { data } = await getaccidentStrip()
  let ccidentStrip = data.map((item) => {
    return {
      year: item.yearList,
      value: item.simTypeNum,
    }
  })
  accidentYrarData.value = ccidentStrip
  // [
  //   { year: '2025', value: 120 },
  //   { year: '2024', value: 200 },
  //   { year: '2023', value: 150 },
  //   { year: '2022', value: 80 },
  //   { year: '2021', value: 70 },
  // ]
}
const viewer = ref(null)
const Cesium = ref(null)
const layerManager = ref(null)
onMounted(async () => {
  console.log('onMounted', showAccident.value)
  getweatherWindapi()
  if (showAccident.value) {
    await getshijian()
    await initChartAccident()
    await getshijiantongji()
    await initChartAccidentyear()
  } else {
    await getshangqing()
    await initChartInjury()
  }
  if (window.viewer && window.Cesium) {
    // 如果已经存在，直接初始化 layerManager
    viewer.value = window.viewer
    Cesium.value = window.Cesium
    layerManager.value = new LayerManager(viewer.value)
    console.log('layerManager initialized from existing viewer', layerManager.value)
  } else {
    // 否则等待事件触发
    window.addEventListener('cesiumInit', cesiumViewInit, true)
  }
  console.log('window.viewer', window.viewer)
  window.addEventListener('resize', resizeChart)
  // window.addEventListener("cesiumInit", cesiumViewInit, true);
})
const cesiumViewInit = (e) => {
  viewer.value = e.detail.viewer
  Cesium.value = e.detail.Cesium
  layerManager.value = new LayerManager(viewer.value)
  console.log('layerManager', layerManager)
}
onActivated(() => {
  titleClick('物资库')
  console.log('onActivated', showAccident.value)
  if (showAccident.value) {
    initChartAccident()
    initChartAccidentyear()
  } else {
    initChartInjury()
  }
  // 组件激活时重新启动定时器和事件监听
  timer = setInterval(async () => {
    if (showAccident.value) {
      await getshijian()
      // await updateChartAccident();
      await getshijiantongji()
      // await updateChartAccidentyear();
    } else {
      await getshangqing()
    }
  }, 5000)
  window.addEventListener('resize', resizeChart)
})
const resizeChart = () => {
  if (chartAccidentInstance) {
    chartAccidentInstance.resize()
  }
  if (chartAccidentYearInstance) {
    chartAccidentYearInstance.resize()
  }
  if (chartInjuryInstance) {
    chartInjuryInstance.resize()
  }
}
onDeactivated(() => {
  // 组件停用时清理定时器和事件监听

  if (timer) clearInterval(timer)
  window.removeEventListener('resize', resizeChart)
  window.removeEventListener('cesiumInit', cesiumViewInit)
  if (chartAccidentInstance) {
    chartAccidentInstance.dispose()
  }
  if (chartAccidentYearInstance) {
    chartAccidentYearInstance.dispose()
  }
  if (chartInjuryInstance) {
    chartInjuryInstance.dispose()
  }
})
onBeforeUnmount(() => {
  window.removeEventListener('cesiumInit', cesiumViewInit)
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  window.removeEventListener('resize', resizeChart)
  if (chartAccidentInstance) {
    chartAccidentInstance.dispose()
    chartAccidentInstance = null
  }
  if (chartAccidentYearInstance) {
    chartAccidentYearInstance.dispose()
    chartAccidentYearInstance = null
  }
  if (chartInjuryInstance) {
    chartInjuryInstance.dispose()
    chartInjuryInstance = null
  }
})

const accidentTableData = ref([])

// 事件列表
const getaccidentListapi = async () => {
  const { data } = await getaccidentList()
  accidentTableData.value = data
  // console.log('accidentTableData.value', accidentTableData.value)
  if (accidentTableData.value.length > 3) {
    isLoop.value = true
  } else {
    isLoop.value = false
  }
}
const fillEmptyRows = (data) => {
  const filled = [...data]
  while (filled.length < 3) {
    filled.push({ name: '无', type: '无', time: '无' })
  }
  return filled
}

const displayData = computed(() => fillEmptyRows(accidentTableData.value))

// const isLoop = computed(() => accidentTableData.value.length > 3)
const isLoop = ref(true)
// 监听 showAccident 变化
watch(
  showAccident,
  async (newVal) => {
    console.log('showAccident changed:', newVal)
    if (newVal) {
      // 图表需要显示时执行
      await getshijian()
      await getshijiantongji()

      // 初始化图表（如果未初始化）
      if (!chartAccidentInstance) {
        await initChartAccident()
      } else {
        // 已初始化则更新尺寸
        chartAccidentInstance.resize()
      }

      if (!chartAccidentYearInstance) {
        await initChartAccidentyear()
      } else {
        chartAccidentYearInstance.resize()
      }
    } else {
      if (!chartInjuryInstance) {
        await initChartInjury()
      } else {
        chartInjuryInstance.resize()
      }
    }
  },
  { immediate: true },
) // immediate: true 确保初始状态也会执行
const swiperIndex = ref(null)
const clickSwiperItem = (item) => {
  swiperIndex.value = item
}
</script>

<style scoped lang="less">
@import './index.less';
</style>
<style>
.jsc-popper-style {
  background: #0b1a2c !important;
}

.jsc-popper-style .el-popper.is-light,
.el-popper.is-light > .el-popper__arrow:before {
  background: linear-gradient(45deg, #64b2ff 50%, #0b1a2c 50%);
}

.jsc-popper-style .el-popper.is-light.el-tooltip.el-popover {
  background-image: url('@/assets/img/jsc/yearbg.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  color: white;
  min-width: 86px;
  padding-left: 0;
  padding-right: 0;
}

/* .jsc-popper-style .el-popper.is-light, .el-popper.is-light > .el-popper__arrow:before{

} */
/* .jsc-popper-style {
  background: #0b1a2c !important;
  background-image: url('@/assets/img/jsc/yearbg.png') !important;
  background-size: cover !important;
  background-repeat: no-repeat !important;
  background-position: center !important;
  color: white !important;
  min-width: 86px !important;
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.custom-popper-style.is-light,
.custom-popper-style.is-light>.el-popper__arrow:before {
  border: none !important;
  background: linear-gradient(45deg, #64b2ff 50%, #0b1a2c 50%) !important;
} */
</style>
